/**
 * @Date: 2022-03-07 19:02:40
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-14 10:48:07
 * @FilePath: \zhihuReal\controllers\userCtl.js
 * @Description: 用户控制器
 */
const jsonwebtoken = require('jsonwebtoken')
const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const User = require('../model/usersMdl')
const Question = require('../model/questionMdl')
const Answer = require('../model/answersMdl')
const Comment = require('../model/commentsMdl')
const {
    secret
} = require('../config')
//获取用户列表
const getUserCtl = async (ctx) => {
    const {
        limit = 10, page = 1
    } = ctx.query
    const pagenum = Math.max(+page, 1) - 1
    const limitnum = Math.max(+limit, 1)
    const list = await User.find({
        userName: new RegExp(ctx.query.keyword)
    }).limit(limitnum).skip(pagenum * limitnum)
    // console.log(list);
    return new SuccessModel(list)
}
//获取特定用户
const getUserByIdCtl = async (ctx) => {
    const {
        fields = ''
    } = ctx.query
    //洗数据 选择性字段过滤 
    const selectFields = fields.split(';').filter(item => item).map(item => ' +' + item).join('')
    const populateStr = fields.split(';').filter(item => item).map(item => {
        if (item === 'employments') {
            return 'employments.company employments.job'
        }
        if (item === 'educations') {
            return 'educations.school educations.majoy'
        }
        return item
    }).join(' ')
    const user = await User.findById(ctx.params.id).select(selectFields).populate(populateStr)
    if (!user) {
        ctx.throw(404, '用户不存在')
    } else {
        return new SuccessModel(user)
    }

}
//创建用户
const createUserCtl = async (ctx) => {
    ctx.verifyParams({
        userName: {
            type: 'string',
            required: true
        },
        password: {
            type: 'string',
            required: true
        }
    })
    const {
        userName
    } = ctx.request.body
    const isRepeated = await User.findOne({
        userName
    })
    if (isRepeated) {
        ctx.throw(409, '用户已经存在')
    }
    const newUser = await User.create(ctx.request.body)
    return new SuccessModel(newUser)
}
//更新用户
const updateUserCtl = async (ctx) => {
    ctx.verifyParams({
        userName: {
            type: 'string',
            required: false
        },
        password: {
            type: 'string',
            required: false
        },
        avatar_url: {
            type: 'string',
            required: false
        },
        gender: {
            type: 'string',
            required: false
        },
        headline: {
            type: 'string',
            required: false
        },
        loactions: {
            type: 'array',
            itemType: 'string',
            required: false
        },
        business: {
            type: 'string',
            required: false
        },
        employments: {
            type: 'array',
            itemType: 'object',
            required: false
        },
        educations: {
            type: 'array',
            itemType: 'object',
            required: false
        },
    })
    const newUser = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    if (!newUser) {
        ctx.throw(404, '你要修改的用户不存在')
        // return new ErrorModel(10004, `你要修改的用户不存在`)
    } else {
        return new SuccessModel(newUser)

    }
}
//删除用户
const deleteUserCtl = async (ctx) => {
    const user = await User.findByIdAndRemove(ctx.params.id)
    console.log(user);
    if (!user) {
        ctx.throw(404, '你要删除的用户不存在')
    } else {
        return 200
    }
}
//登陆
const Userlogin = async (ctx) => {
    // console.log(ctx.request.body);
    ctx.verifyParams({
        userName: {
            type: 'string',
            required: true
        },
        password: {
            type: 'string',
            required: true
        }
    })
    const user = await User.findOne(ctx.request.body)
    if (!user) {
        ctx.throw(401, '用户名或者密码不正确')
    }
    //生成token
    const {
        _id,
        userName
    } = user
    const token = jsonwebtoken.sign({
        _id,
        userName
    }, secret, {
        expiresIn: '3d'
    })
    return new SuccessModel({
        token: token
    })
}
//获取关注列表
const followingList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+following').populate('following')
    console.log(user);
    if (!user) {
        ctx.throw(404)
    }
    return new SuccessModel(user.following)
}
//获取粉丝列表
const followerList = async (ctx) => {

    const list = await User.find({
        following: ctx.params.id
    })
    console.log(list);
    return new SuccessModel(list)
}
//关注某人
const follow = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+following')
    if (!me.following.map(id => id.toString()).includes(ctx.params.id)) {
        me.following.push(ctx.params.id);
        me.save()
    }
    ctx.status = 204
}
//取消关注
const unFollow = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+followingTopics')
    const index = me.followingTopics.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.followingTopics.splice(index, 1);
        me.save()
    }
    ctx.status = 204
}
//关注话题
const followTopic = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+followingTopics')
    console.log(!me.followingTopics.map(id => id.toString()).includes(ctx.params.id));
    if (!me.followingTopics.map(id => id.toString()).includes(ctx.params.id)) {
        me.followingTopics.push(ctx.params.id);
        me.save()
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//取消关注话题
const unFollowTopic = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+followingTopics')
    const index = me.followingTopics.map(id => id.toString()).indexOf(ctx.params.id)
    console.log(index);
    if (index > -1) {
        me.followingTopics.splice(index, 1);
        me.save()
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//关注问题
const followQuestion = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+followingQuestions')
    if (!me.followingQuestions.map(id => id.toString()).includes(ctx.params.id)) {
        me.followingQuestions.push(ctx.params.id);
        me.save()
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//取消关注问题
const unFollowQuestion = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+followingQuestions')
    const index = me.followingQuestions.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.followingQuestions.splice(index, 1);
        me.save()
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//获取关注的话题列表
const followingTopicList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+followingTopics').populate('followingTopics')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.followingTopics)
}
//获取提问列表
const questionList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+followingQuestions').populate('followingQuestions')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.followingQuestions)
}
//点赞答案列表
const likeAnswersList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+likeAnswerList').populate('likeAnswerList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.likeAnswerList)
}
//点赞答案
const LikeAnswers = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+likeAnswerList')
    if (!me.likeAnswerList.map(id => id.toString()).includes(ctx.params.id)) {
        me.likeAnswerList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                likeCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消点赞答案
const disLikeAnswers = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+likeAnswerList')
    const index = me.likeAnswerList.map(id => id.toString()).indexOf(ctx.params.id)
    console.log(index);
    if (index > -1) {
        me.likeAnswerList.splice(index, 1);
        me.save()
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                likeCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//收藏答案列表
const collectionAnswersList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+collectionAnswerList').populate('collectionAnswerList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.collectionAnswerList)
}
//收藏答案
const collectionAnswers = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+collectionAnswerList')
    const index = me.collectionAnswerList.map(id => id.toString()).indexOf(ctx.params.id)
    if (!me.collectionAnswerList.map(id => id.toString()).includes(ctx.params.id)) {
        me.collectionAnswerList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                collectionCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消收藏答案
const disCollectionAnswers = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+collectionAnswerList')
    const index = me.collectionAnswerList.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.collectionAnswerList.splice(index, 1);
        me.save()
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                collectionCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//踩答案列表
const unlikeAnswersList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+unLikeAnswerList').populate('unLikeAnswerList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.unLikeAnswerList)
}
//踩答案
const unLikeAnswers = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+unLikeAnswerList')
    const index = me.unLikeAnswerList.map(id => id.toString()).indexOf(ctx.params.id)
    if (!me.unLikeAnswerList.map(id => id.toString()).includes(ctx.params.id)) {
        me.unLikeAnswerList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                unlikeCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消踩答案
const disunlikeAnswers = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+unLikeAnswerList')
    const index = me.unLikeAnswerList.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.unLikeAnswerList.splice(index, 1);
        me.save()
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                unlikeCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//踩评论列表
const unlikeCommentList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+unLikeCommentList').populate('unLikeCommentList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.unLikeCommentList)
}
//踩评论
const unLikeComment = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+unLikeCommentList')
    if (!me.unLikeCommentList.map(id => id.toString()).includes(ctx.params.id)) {
        me.unLikeCommentList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Comment.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                unlikeCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消踩评论
const disunlikeComment = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+unLikeCommentList')
    const index = me.unLikeCommentList.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.unLikeCommentList.splice(index, 1);
        me.save()
        await Comment.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                unlikeCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//收藏评论列表
const collectionCommentList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+collectionCommentList').populate('collectionCommentList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.collectionCommentList)
}
//收藏评论
const collectionComment = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+collectionCommentList')
    const index = me.collectionCommentList.map(id => id.toString()).indexOf(ctx.params.id)
    if (!me.collectionCommentList.map(id => id.toString()).includes(ctx.params.id)) {
        me.collectionCommentList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Comment.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                collectionCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消收藏评论
const disCollectionComment = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+collectionCommentList')
    const index = me.collectionCommentList.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.collectionCommentList.splice(index, 1);
        me.save()
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                collectionCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//点赞评论列表
const likeCommentList = async (ctx) => {
    const user = await User.findById(ctx.params.id).select('+likeCommentList').populate('likeCommentList')
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    ctx.body = new SuccessModel(user.likeCommentList)
}
//点赞评论
const LikeComment = async (ctx, next) => {
    const me = await User.findById(ctx.state.user._id).select('+likeCommentList')
    if (!me.likeCommentList.map(id => id.toString()).includes(ctx.params.id)) {
        me.likeCommentList.push(ctx.params.id);
        me.save()
        //投票数加一
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                likeCount: 1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
    await next()
}
//取消点赞评论
const disLikeComment = async (ctx) => {
    const me = await User.findById(ctx.state.user._id).select('+likeCommentList')
    const index = me.likeCommentList.map(id => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
        me.likeCommentList.splice(index, 1);
        me.save()
        await Answer.findByIdAndUpdate(ctx.params.id, {
            $inc: {
                likeCount: -1
            }
        })
    }
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//授权
const cheackOwner = async (ctx, next) => {
    console.log(ctx.params.id !== ctx.state.user._id);
    if (ctx.params.id !== ctx.state.user._id) {
        ctx.throw(403, '您没有此权限')
    }
    await next()
}
module.exports = {
    getUserCtl,
    getUserByIdCtl,
    createUserCtl,
    updateUserCtl,
    deleteUserCtl,
    Userlogin,
    cheackOwner,
    followingList,
    follow,
    unFollow,
    followerList,
    followTopic,
    unFollowTopic,
    followingTopicList,
    questionList,
    unFollowQuestion,
    followQuestion,
    likeAnswersList,
    LikeAnswers,
    disLikeAnswers,
    unlikeAnswersList,
    unLikeAnswers,
    disunlikeAnswers,
    collectionAnswersList,
    collectionAnswers,
    disCollectionAnswers,
    unlikeCommentList,
    unLikeComment,
    disunlikeComment,
    collectionCommentList,
    collectionComment,
    disCollectionComment,
    likeCommentList,
    LikeComment,
    disLikeComment
}